import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

void main(List<String> args) {
  runApp(MainPage());
}

class MainPage extends StatefulWidget {
  MainPage({Key? key}) : super(key: key);

  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //发起网络请求
    _getChannels();
  }
  //定义一个列表，用来存储请求到的数据
  List<Map<String,dynamic>> _list = [];
  void _getChannels()async{
    //发起网络请求
    Response<dynamic> res = await DioUtils().get("channels");
    Map<String,dynamic> result = res.data as Map<String,dynamic>;
    List data = result["data"]["channels"] as List;
    _list =data.cast<Map<String,dynamic>>() as List<Map<String,dynamic>>;
    setState(() {
      
    });
    print(_list);
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home:Scaffold(
        appBar:AppBar(title:Text("Dio工具类显示数据"),) ,
        body:GridView.extent(maxCrossAxisExtent: 140,
        padding: EdgeInsets.all(10),
        mainAxisSpacing: 10,
        crossAxisSpacing: 10,
        childAspectRatio: 1.5,
        children:List.generate(_list.length, (index) {
          return ChannelItem(item:_list[index]);
        })
        )
      )
    );
  }
}
class ChannelItem extends StatelessWidget {
  final Map<String,dynamic> item;
  const ChannelItem({Key? key,required this.item}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.blue,
      alignment: Alignment.center,
      child: Text(item["name"]??"空",style: TextStyle(fontSize: 20,color: Colors.white),),
    );
  }
}
//封装一个工具类
class DioUtils{
  final Dio _dio = Dio();
  DioUtils(){
    // _dio.options.baseUrl = "https://geek.itheima.net/v1_0/";
    // _dio.options.connectTimeout = Duration(seconds: 10);//连接超时时间
    // _dio.options.sendTimeout = Duration(seconds: 10);//发送超时时间
    // _dio.options.receiveTimeout = Duration(seconds: 10);//接收超时时间
    //简写..连续赋值的写法
    _dio.options
    ..baseUrl="https://geek.itheima.net/v1_0/"
    ..connectTimeout=Duration(seconds: 10)
    ..sendTimeout=Duration(seconds: 10)
    ..receiveTimeout=Duration(seconds: 10);

    //添加拦截器
    _addInterceptors();
    
  }


  void _addInterceptors(){
    _dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options,handler){
        // handler.reject(error)拦截请求
        //在请求之前做一些事情
        handler.next(options);
      },
      onResponse: (response,handler){
        if(response.statusCode!>=200 && response.statusCode!<=300){
          handler.next(response);//继续传递响应
          return;
        }
        //处理异常
        handler.reject(DioException(
          requestOptions: response.requestOptions,
          response: response,
          message: "状态码${response.statusCode}"
        ));
      },
      onError: (DioException e,handler){
        handler.reject(e);
      }
    ));
  }

//向外暴露一个get方法
Future<Response<dynamic>> get(String url,{Map<String,dynamic>? queryParameters})async{

    return await _dio.get(url,queryParameters: queryParameters);
  
}
}